<template>
  <div class="OrderList">
    <van-nav-bar
      title="订单确认"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <div class="address">
      <h2>您的收货地址</h2>
      <div class="addresscon" @click="goAddressList()">
        <div class="addressLeft">
          <span>收件人：{{ userAddress.receiver }}</span>
          <span>{{ userAddress.mobile }}</span>
          <p>收件地址：{{ userAddress.regions }}-{{ userAddress.address }}</p>
        </div>
        <van-icon name="arrow" />
      </div>
      <div class="shippingMethod">
        <div class="shippingMethodsTop">
          <van-icon name="free-postage" />
          普通送货
        </div>
        <div class="shippingMethodsFoot">
          标准配送，下单后通过货车或包裹形式送达
        </div>
      </div>
    </div>

    <div class="order">
      <h2>您的商品清单</h2>
      <div class="shipping"><van-icon name="cart-circle-o" />货车配送</div>
      <van-cell
        title="送达时间     点击选择"
        :value="date"
        @click="show = true"
        class="time"
      />
      <van-calendar v-model="show" @confirm="onConfirm" color="#0159A1" />
      <p class="time1">请确认预计配送时间，点击日期可修改</p>
      <div v-for="item in lists" :key="item.order._id">
        <p class="dingdan">
          <van-icon name="after-sale" />订单编号:{{ item.order._id }}
        </p>
        <van-card
          v-for="pro in item.details"
          :key="pro._id"
          :num="pro.quantity"
          :price="(pro.price / 100).toFixed(2)"
          :desc="pro.product.name"
          :thumb="pro.product.coverImg"
        />
      </div>
    </div>

    <div class="orderDetail">
      <h2>订单明细</h2>
      <p>
        <span>商品合计</span>
        <span>￥{{ countPrice }}</span>
      </p>
      <p>
        <span>配送费</span>
        <span>￥0.00</span>
      </p>
      <p>
        <span>优惠券</span>
        <span>暂无可用</span>
      </p>
      <hr />
      <p class="count">
        <span style="font-weight: bold; color: #000">实付</span>
        <span style="font-weight: bold; color: #000; font-size: 20px"
          >￥{{ countPrice }}</span
        >
      </p>
    </div>

    <div style="padding: 15px; background: #fff">
      <van-goods-action-button
        type="danger"
        text="立即付款"
        @click="onClickButton(ids)"
        color="#0158A0"
      />
    </div>
  </div>
</template>

<script>
//引入vant轻提示模块
import { Dialog, Toast } from "vant";
//引入获取收货地址接口,获取订单详情接口
import {
  reqGetAdderssAPI,
  reqGetOrderDetailAPI,
  reqpayAPI,
} from "../../api/order";
export default {
  data() {
    return {
      date: "",
      show: false,
      // 每页显示数量
      per: 10,
      page: 1,
      userAddress: {},
      addrs: [],
      // ids: [],
      lists: [],
      fromroute: "",
    };
  },

  watch: {
    $route(to, from) {
      console.log(to);
      console.log(from);
    },
  },
  beforeRouteEnter(to, from, next) {
    // ...
    // ...
    console.log(to);
    console.log(from);
    console.log(next);
    if (from.path == "/cart") {
      next((vm) => {
        vm.fromroute = "/cart";
      });
    } else if (from.path == "/addresslist") {
      next((vm) => {
        // vm.fromroute='/orderlist';
        vm.fromroute = "/addresslist";
      });
    } else if (from.path == "/AllOrderList/nopayorder") {
      next((vm) => {
        vm.fromroute = "/AllOrderList/nopayorder";
      });
    } else if (from.path == "/AllOrderList/payorder") {
      next((vm) => {
        vm.fromroute = "/AllOrderList/payorder";
      });
    }
    next();
  },

  methods: {
    //选择商品送达时间
    formatDate(date) {
      return `${date.getMonth() + 1}/${date.getDate()}`;
    },
    onConfirm(date) {
      this.show = false;
      this.date = this.formatDate(date);
    },

    //点击返回时，返回到上一个页面
    onClickLeft() {
      this.$router.push("/cart");
      if (
        this.fromroute == "/AllOrderList/nopayorder" ||
        this.fromroute == "/AllOrderList/payorder"
      ) {
        this.$router.push("/AllOrderList/nopayorder");
      }
    },
    //进入订单列表后 从数据库中读取收货地址 判断收货地址中哪一个是默认收获地址，
    //如果有默认收货地址，就展示默认收货地址，如果没有，就展示第一个收获地址
    async getAddress() {
      //发起获取收货地址请求
      const result = await reqGetAdderssAPI({ per: this.per, page: this.page });
      console.log(result);
      //如果收货地址没有就跳到添加地址
      if (result.addresses.length === 0) {
        this.$router.push("/addaddr2");
      } else {
        console.log(this.lists);
        //有地址就用户在地址列表有没有选择地址，即有没有传来地址id
        console.log(this.fromroute);
        if (this.fromroute == "/addresslist") {
          console.log(11111111);
          if (this.$route.params.id) {
            //传有地址id 就在数据库中找到对应的地址渲染页面
            console.log(result);
            // console.log(this.$route.params.ids);
            result.addresses.forEach((address) => {
              if (address._id == this.$route.params.id) {
                this.userAddress = address;
              }
            });
          }
        } else {
          //如果没有传id 就直接从数据库的地址中选取
          //判定拿到的收货地址中是否有默认收货地址
          result.addresses.forEach((address) => {
            //拿到每一个地址 对是否是默认收货地址进行判断
            if (address.isDefault === true) {
              //如果是默认收货地址，就直接使用
              this.userAddress = address;
            }
            //将所有地址的是否默认收货地址放到一个数组中
            this.addrs.push(address.isDefault);
          });
          console.log(this.addrs);
          // //如果没有默认收货地址，就使用第一个
          const flag = this.addrs.every((v) => v === false);
          if (flag === true) {
            this.userAddress = result.addresses[0];
            console.log(this.userAddress);
          }
        }

        console.log(result);
      }
    },

    //点击收货地址信息，弹出弹框，确定修改跳转到地址列表进行选择
    goAddressList() {
      Dialog.confirm({
        title: "地址修改",
        message: "确定修改您的收货地址吗？",
      })
        .then(() => {
          this.$router.push("/addresslist");
        })
        .catch(() => {});
    },

    //获取用户提交的订单列表
    getOrderDetailList() {
      if (this.$route.params.ids) {
        console.log(this.$route.params.ids);
        //拿到购物车提交过来的订单ids
        localStorage.setItem(
          "orderids",
          JSON.stringify(this.$route.params.ids)
        );
      }
      this.ids = JSON.parse(localStorage.getItem("orderids"));
      // 对拿到的ids进行循环遍历，依次发起请求拿到订单详情
      this.ids.forEach((id) => {
        reqGetOrderDetailAPI(id).then((res) => {
          //   // 将拿到的订单详情保存到订单列表的数组中，用来渲染页面
          this.lists.push(res);
        });
        // console.log(this.lists);
      });
    },
    //点击立即付款按钮
    async onClickButton() {
      Toast("购买成功");
      let ids = JSON.parse(localStorage.getItem("orderids"));
      const result = await reqpayAPI(ids);
      console.log(result);
      this.$router.push("/buy");
    },
  },

  created() {
    //调用获取默认地址的函数
    console.log(this.$route.params.id);

    this.getAddress();

    //调用获取订单详情
    this.getOrderDetailList();
  },

  computed: {
    countPrice() {
      //用来存放总价
      let count = 0;
      //先过滤所有选中的商品 拿到所有的选中的商品后 进行循环遍历 将他们的商品数量*商品价格相加
      this.lists.forEach((order) => {
        order.details.forEach((pro) => {
          count += (pro.price / 100) * pro.quantity;
        });
      });
      return count.toFixed(2);
    },
  },
};
</script>

<style>
.OrderList {
  background-color: #f5f5f5;
  overflow: hidden;
}
.address,
.order {
  padding: 20px;
  text-align: left;
  background-color: #fff;
}
.address h2 {
  height: 30px;
  font-size: 16px;
  font-weight: bold;
}
.addresscon {
  display: flex;
  height: 50px;
  font-size: 14px;
  line-height: 25px;
  justify-content: space-between;
}
.addressLeft p {
  color: #939393;
}
.van-icon-arrow {
  height: 50px;
  line-height: 50px;
}
.shipping .van-icon {
  font-size: 18px;
  font-weight: bold;
  margin-right: 5px;
}
.shippingMethod {
  margin-top: 15px;
}
.shippingMethod div {
  height: 40px;
  line-height: 20px;
  background: #f5f5f5;
  overflow: hidden;
  padding: 10px;
  box-sizing: border-box;
  font-size: 12px;
}
.shippingMethod div:first-of-type {
  font-weight: bold;
  border-bottom: 1px solid #ededed;
  font-size: 14px;
}
.shippingMethod div:last-of-type {
  color: #868686;
}
.shippingMethod .van-icon {
  font-size: 20px;
}
.order {
  margin-top: 10px;
}
.order h2 {
  height: 30px;
  font-size: 16px;
  font-weight: bold;
}
.shipping {
  height: 25px;
  font-size: 14px;
  line-height: 25px;
  font-weight: bold;
}
.time,
.time1 {
  color: #979797;
}
.time1 {
  font-size: 12px;
  padding: 15px;
}
.orderDetail {
  background-color: #fff;
  margin-top: 10px;
  text-align: left;
  padding: 20px;
}
.orderDetail h2 {
  height: 30px;
  font-size: 16px;
  font-weight: bold;
}
.orderDetail p {
  font-size: 14px;
  color: #979797;
  line-height: 30px;
  height: 30px;
  display: flex;
  justify-content: space-between;
}
.dingdan {
  font-size: 14px;
  color: #3a3939;
  margin: 30px 0 10px 0;
  height: 20px;
  line-height: 20px;
}
.dingdan i {
  font-size: 20px;
  margin-right: 5px;
}
</style>
